package com.treasure.web.interceptor;

import com.treasure.common.model.TraceIdHolder;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sunhongmin
 * @date 2023/9/1 17:44
 * @description
 */
@Component
@Order(1)
public class TraceIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 生成链路追踪ID
        String traceId = TraceIdHolder.genTraceId();
        // 保存到线程上下文
        TraceIdHolder.setTraceId(traceId);
        // 存入MDC，用于日志中显示
        MDC.put("traceId", traceId);
        // 链路追踪ID加入响应信息头
        response.setHeader("traceId", traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求结束时清空上下文，防止内存泄漏
        TraceIdHolder.clear();
    }
}
